import request from '@/request.js'
import config from '@/config.js'

import imageShow from '@/components/imageShow/imageShow.vue'

export default {
  name: 'autotileManage',
  components: {
    imageShow
  },
  data () {
    return {
      isLoading: true,
      // AutoTile数据
      autoTilesData: [],
      autoTileSelected: '',
      
      uploadModal: false,
      uploadApi: config.apiPath + 'addAutotile',
    }
  },
  methods: {
    uploadHandler () {
      this.uploadModal = true
      this.$refs.autotileUpload.clearFiles()
    },
    
    uploadSuccess (res) {
      // 文件上传接口返回图片路径
      this.$Notice.success({
        title: '上传AutoTile成功'
      })
      if (this.autoTilesData.indexOf(res) < 0) {
        this.autoTilesData.unshift(res)
      }
    },
    
    uploadFailed () {
      this.$Notice.error({
        title: '上传AutoTile出错，可能是图片尺寸不符合要求'
      })
    },
    
    selectAutoTile (autotile) {
      this.autoTileSelected = autotile
    },
    
    deleteAutoTile (autotile) {
      console.log(autotile)
      const index = this.autoTilesData.indexOf(autotile)
      // 获取名称
      const lastIndex = autotile.lastIndexOf('/')
      autotile = autotile.slice(lastIndex + 1)
      // 去除后缀
      let arr = autotile.split('.')
      arr.splice(arr.length - 1, 1)
      autotile = arr.join('.')
      
      this.$Modal.confirm({
        title: '删除AutoTile',
        content: '是否删除当前AutoTile: ' + autotile,
        loading: true,
        onOk: () => {
          request.deleteAutoTile(autotile).then((data) => {
            this.$Notice.success({
              title: '删除AutoTile成功'
            })
            // 去掉被选中的图片
            this.autoTilesData.splice(index, 1)
            this.autoTileSelected = ''
            this.$Modal.remove()
          })
          .catch((err) => {
            console.log(err)
            this.$Notice.error({
              title: '删除AutoTile出错'
            })
            this.$Modal.remove()
          })
        }
      })
    }
  },
  created () {
    request.getAutoTile().then((data) => {
      this.autoTilesData = data
      this.isLoading = false
      this.$Notice.success({
        title: '获取AutoTile成功'
      })
    })
    .catch((err) => {
      console.log(err)
      this.$Notice.error({
        title: '获取AutoTile出错'
      })
    })
  }
}